Ext.namespace("MyApp.common"); // For the stuff added below

// Common setting changes of Ext JS
Ext.Ajax.disableCaching = false;

// Common functions
MyApp.common.handleFormSubmit = function (url, id, doThisOnSuccess) {
  return function (form) {
    form.submit({
      waitMsg:'Sending data...',
      method: id==null?"POST":"PUT",
      url: url + (id==null?"":"/"+encodeURIComponent(id)),
      headers: { "Accept": "application/json" },
      success: doThisOnSuccess,
      failure: MyApp.common.handleFormSubmitFailure
    });
  };
};

MyApp.common.handleFormSubmitFailure = function (form, response) {
//  switch (action.failureType) {
//    case Ext.form.Action.CLIENT_INVALID:
//      Ext.Msg.alert('Failure: CLIENT_INVALID', 'Form fields may not be submitted with invalid values');
//      break;
//    case Ext.form.Action.CONNECT_FAILURE:
//      MyApp.common.displayFailure('Failure: CONNECT_FAILURE', action.response);
//      break;
//    case Ext.form.Action.SERVER_INVALID:
//      if(action.result.msg) {
//        Ext.Msg.alert('Failure: SERVER_INVALID', '<b>'+action.result.msg+'</b>'+(action.result.longmsg?'<br>'+action.result.longmsg:''));
//      }
//      break;
//    default:
      MyApp.common.displayFailure('Failure: default', response);
//      break;
//  }
};

MyApp.common.loadForm = function (formPanel, url, id) {
  if(id != null) {
    formPanel.getForm().load({
      url: url + '/' + encodeURIComponent(id),
      method: "GET",
      headers: { "Accept": "application/json" },
      waitMsg: 'Loading...',
      failure: MyApp.common.handleFormLoadFailure
    });
  }
};

MyApp.common.handleFormLoadFailure = function (form, action) {
  switch (action.failureType) {
    case Ext.form.Action.CONNECT_FAILURE:
      MyApp.common.displayFailure('Failure: CONNECT_FAILURE', action.response, function() {history.go(-1);});
      break;
    case Ext.form.Action.LOAD_FAILURE:
      MyApp.common.displayFailure('Failure: LOAD_FAILURE', action.response, function() {history.go(-1);});
      break;
    default:
      MyApp.common.displayFailure('Failure: default', action.response, function() {history.go(-1);});
      break;
  }
};

MyApp.common.handleStoreLoadException = function (dataproxy, response, operation) {
  MyApp.common.displayFailure('Failure', response);
};

MyApp.common.decodeJson = function (responseText) {
  try {
    return Ext.decode(responseText);
  } catch (Error) {
    //Ext.Msg.alert('Json parsing failed: ' + Error);
    return null;
  }
};

MyApp.common.displayFailure = function (title, response, doAfterMessage) {
  if(response.status == 401) {
    MyApp.common.login.refreshLoginData(function () {
      if(MyApp.common.login.getLoginData().loggedIn == true) {
        // TODO
        Ext.Msg.alert(title, 'Wrong role');
      } else {
        MyApp.views.logout_confirmation.logout_confirmation.display();
      }
    });
  } else {
    title = title + " (" + response.status + " " + response.statusText + ")";
    
    if(response.responseText) {
      var jsonResponse = MyApp.common.decodeJson(response.responseText);
      
      if(jsonResponse != null) {
        if(jsonResponse.success) {
          Ext.Msg.alert('Ended up in Exception handler, despite success:true. Odd.', '<b>'+jsonResponse.msg+'</b>'+(jsonResponse.longmsg?'<br>'+jsonResponse.longmsg:''), doAfterMessage);
        } else if (jsonResponse.msg) {
          Ext.Msg.alert(title, '<b>'+jsonResponse.msg+'</b>'+(jsonResponse.longmsg?'<br>'+jsonResponse.longmsg:''), doAfterMessage);
        } else {
          Ext.Msg.alert(title, 'No reason given.', doAfterMessage);        
        }
      } else {
        new Ext.Panel({
          floating: true,
          modal: true,
          centered: true,
          scroll: 'vertical',
          dockedItems: [{
            dock: 'top',
            xtype: 'toolbar',
            title: title
          }],
          styleHtmlContent: true,
          html: response.responseText,
          listeners: {
            show: function (panel) {
              if(panel.getWidth() < Ext.getBody().getWidth() && panel.getHeight() < Ext.getBody().getHeight()) {
                panel.center();
                Ext.getBody().mask();
              }
            },
            close: function () {
              Ext.getBody().unmask();
            }
          }
        }).show();
      }
    } else {
      Ext.Msg.alert(title, "No responseText", doAfterMessage);
    }
  }
};

MyApp.common.sendJsonRequestAndDoOnSuccess = function (config, doThisOnSuccess) {
  var defaultConfig = {
    headers: { "Accept": "application/json" },
    loadIndicator: true,
    messageBeforeSuccessAction: true,
    success: function(response, opts) {
      hideLoadIndicator();
      
      var jsonResponse = MyApp.common.decodeJson(response.responseText);

      if(response.status = 200 && jsonResponse != null && jsonResponse.success) {
        if(jsonResponse.msg) {
          Ext.Msg.alert('Success', '<b>'+jsonResponse.msg+'</b>'+(jsonResponse.longmsg?'<br>'+jsonResponse.longmsg:''), function() {
            if(messageBeforeSuccessAction) {
              doThisOnSuccess(jsonResponse, response, opts);
            }
          });
        }
        
        if(!messageBeforeSuccessAction || !jsonResponse.msg) {
          doThisOnSuccess(jsonResponse, response, opts);
        }
      } else {
        MyApp.common.displayFailure('Failure ' + opts.url, response);
      }
    },
    failure: function (response, opts) {
      hideLoadIndicator();

      MyApp.common.displayFailure('Failure: ' + opts.url, response);
    }
  };
  
  var hideLoadIndicator = function() {
    if(typeof loadMask != "undefined") {
      loadMask.hide();
    }
  };
  
  var actualConfig = {};
  Ext.apply(actualConfig, config, defaultConfig);

  var loadMask;
  
  if(typeof actualConfig.loadIndicator != "undefined") {
    var maskElement = null;
    if(typeof actualConfig.loadIndicator == "string") {
      maskElement = Ext.get(actualConfig.loadIndicator);
    } else if(actualConfig.loadIndicator == true) {
      maskElement = Ext.get(Ext.getBody());
    }

    if(maskElement != null) {
      loadMask = new Ext.LoadMask(maskElement);
      loadMask.show();
    }
  }
  
  actualConfig.loadIndicator = null;

  var messageBeforeSuccessAction = actualConfig.messageBeforeSuccessAction;
  actualConfig.messageBeforeSuccessAction = null;
  
  Ext.Ajax.request(actualConfig);
};
